package com.dennytech.tac.widget;

import java.io.InputStream;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;

public class LocalImageTextView extends ImageTextView {
	AssetManager assets;

	public LocalImageTextView(Context context) {
		super(context);
		assets = context.getResources().getAssets();
	}

	public LocalImageTextView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		assets = context.getResources().getAssets();
	}

	public LocalImageTextView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public void addImage(String url, int postion) {
		addImage(readBitmap(url), postion);
	}

	private Bitmap readBitmap(String url) {
		int i = url.lastIndexOf("/");
		if (i > 0) {
			NetworkImageView.urlLocks.lock(url);
			try {
				//
				// check memcache first
				//
				Bitmap cbitmap = NetworkImageView.memcache.get(url);
				if (cbitmap != null)
					return cbitmap;
				String icon = url.substring(i + 1);
				InputStream ins = assets.open("localicon/" + icon);
				Bitmap bitmap = BitmapFactory.decodeStream(ins);
				ins.close();
				if (bitmap != null)
					NetworkImageView.memcache.put(url, bitmap);
				return bitmap;
			} catch (Exception e) {
			} finally {
				NetworkImageView.urlLocks.unlock(url);
			}
		}
		
		return null;
	}
}
